import logging
from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, List, Any, Optional

from ..database.connector import DatabaseConnector
from ..database.schema_reader import SchemaReader
from ..query.query_generator import QueryGenerator
from ..chart.chart_generator import ChartGenerator
from .models import (
    QueryRequest, 
    ChartConfigRequest,
    QueryResponse
)

router = APIRouter(prefix="/api", tags=["text-to-chart"])

_db_connector = DatabaseConnector()
_schema_reader = None
_query_generator = QueryGenerator()
_chart_generator = ChartGenerator()
_logger = logging.getLogger(__name__)

def initialize_database():
    _db_connector.connect()
    global _schema_reader
    _schema_reader = SchemaReader(_db_connector)
    _schema_reader.read_all_tables()

initialize_database()

@router.post("/query", response_model=QueryResponse)
async def process_query(
    request: QueryRequest
):
    db_schema = _schema_reader.get_schema_for_llm()
    database_name = _db_connector.database
    sql = _query_generator.generate_sql(request.query, db_schema, database_name)
    data = _db_connector.execute_query(sql)
    if not data or len(data) == 0:
        empty_chart_config = {
            "title": {"text": "没有数据"},
            "tooltip": {},
            "series": []
        }
        return QueryResponse(
            sql=sql,
            data=[],
            chart_config=empty_chart_config
        )
    chart_config = _chart_generator.generate_chart_config(data, request.query)
    return QueryResponse(
        sql=sql,
        data=data,
        chart_config=chart_config
    )

@router.post("/chart", response_model=Dict[str, Any])
async def generate_chart(request: ChartConfigRequest):
    chart_config = _chart_generator.generate_chart_config(
        data=request.data,
        user_query=request.query,
        chart_type=request.chart_type
    )
    return chart_config